package cn.itcast.bos.web.action;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.take_delivery.WayBill;
import cn.itcast.bos.service.WayBillService;
import cn.itcast.bos.web.action.common.BaseAction;

@ParentPackage(value="json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class WayBillAction extends BaseAction<WayBill> {

	//如果需要写入日志，可以使用
	private static final  Logger logger = Logger.getLogger(WayBillAction.class);
	@Autowired
	private WayBillService wayBillService;
	
	/**
	 * 快递录入运单的保存功能
	 * @return
	 */
	@Action(value = "waybill_save", results = { @Result(name = "success", type = "json") })
	public String save() {
		
		//防止瞬时对象异常
		if (model.getOrder()!=null&&(model.getOrder().getId()==null || model.getOrder().getId()==0)) {
			model.setOrder(null);
		}
		
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			wayBillService.save(model);
			result.put("success", true);
			result.put("msg", "保存运单成功！");
			logger.info("保存运单成功，运单号："+model.getWayBillNum());
		} catch (Exception e) {
			result.put("success", false);
			e.printStackTrace();
			logger.error("保存运单失败，运单号：" + model.getWayBillNum(), e);
		}
		ServletActionContext.getContext().getValueStack().push(result);
		return SUCCESS;
	}
	
	
	@Action(value = "waybill_pageQuery", results = { @Result(name = "success", type = "json") })
	public String pageQuery() {
		//无条件查询
		Pageable pageable = new PageRequest(page-1, rows,new Sort(new Sort.Order(Sort.Direction.ASC,"id")));
		//调用业务层,进行查询
		Page<WayBill> pageData=wayBillService.findAll(model,pageable);
		pushPageDataToValueStack(pageData);
		
		return SUCCESS;
	}
	
	//完成运单回显
	@Action(value = "waybill_findByWayBillNum", results = { @Result(name = "success", type = "json") })
	public String findByWayBillNum() {
		Map<String, Object> result = new HashMap<String, Object>();
		WayBill wayBill=wayBillService.findByWayBillNum(model.getWayBillNum());
		if (wayBill==null) {
			//运单不存在
			result.put("success", false);
		}else {
			//运单存在
			result.put("success", true);
			result.put("wayBillData", wayBill);
			
		}
		ServletActionContext.getContext().getValueStack().push(result);
		return SUCCESS;
	}
	
	
}
